package blackspire.service.user;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import blackspire.model.user.User;

@Transactional
public class UserServiceImpl implements UserService
{
	private EntityManager em;

	@PersistenceContext
	public void setEntityManager(EntityManager em)
	{
		this.em = em;
	}

	@SuppressWarnings("unchecked")
	public List<User> findAll()
	{
		Query query = getEntityManager().createQuery("select u FROM User u");
		return query.getResultList();
	}

	public void save(User user)
	{
		if (user.getId() == null)
		{
			// new
			em.persist(user);
		} else
		{
			// update
			em.merge(user);
		}
	}

	public void remove(int id)
	{
		User user = find(id);
		if (user != null)
		{
			em.remove(user);
		}
	}

	private EntityManager getEntityManager()
	{
		return em;
	}

	public User find(int id)
	{
		return em.find(User.class, id);
	}

	public User find(String emailAddress)
	{

		Query query = getEntityManager().createQuery("select u FROM User u where emailAddress = '" + emailAddress + "'");

		User user = null;

		try
		{
			user = (User) query.getSingleResult();
		} catch (Exception ex)
		{

		}

		return user;

	}

}
